import os
import sys
from subprocess import getoutput

import plbm
from loguru import logger


class BuildDeb:
	def __init__(self, arm64=True, amd64=True, mips64=False, all=False):
		"""
		自动构建deb包
		:param arm64: 构建arm包
		:param amd64: 构建amd包
		:param mips64: 构建mips包
		"""
		self.all = all
		self.version = "1.3.0"
		self.work = os.getcwd()
		self.mips64 = mips64
		self.amd64 = amd64
		self.arm64 = arm64
		self.home = plbm.home_dir
		self.pack_root = os.path.join(self.home, f"com.liumou.pings_{self.version}")
		self.usr_bin_dir = os.path.join(self.pack_root, "usr/bin")
		self.usr_bin_client = os.path.join(self.usr_bin_dir, "pings")
		self.debian = os.path.join(self.pack_root, "DEBIAN")
		self.postinst = os.path.join(self.debian, "postinst")
		self.postrm = os.path.join(self.debian, "postrm")
		self.control = os.path.join(self.pack_root, "DEBIAN/control")
		self.pack_apps = os.path.join(self.pack_root, "opt/apps")
		self.build_apps_pack = os.path.join(self.pack_apps, "com.liumou.pings")
		self.files = os.path.join(self.build_apps_pack, "files")
		self.text = ""
		self.client = f"com.liumou.pings_all-{self.version}.deb"
		self.build_client = os.path.join(self.home, f"com.liumou.pings_{self.version}.deb")
		self.dst = f"/root/git/Nginx/html/clm/pings"
		os.system(f"mkdir -p {self.dst}")
		self.dst = f"{self.dst}/{self.client}"
		self.set_arch = "all"
		self.arch = getoutput("uname -m")
		if self.arch == "x86_64":
			self.arch = "amd64"
		if self.arch == "aarch64":
			self.arch = "arm64"
		if self.arch == "mips64":
			self.arch = "mips64le"
		self.build_arch_list = ["liumou"]
		self.publish_list = []
		self.init()
		self.work = os.getcwd()

	def init(self):
		if os.path.isdir(self.pack_root):
			os.system(f"rm -rf {self.pack_root}")
		self.cp_cmd(src="./BuildDeb/com.liumou.pings", dst=self.pack_root, name="init")
		if self.arm64:
			self.build_arch_list.append("arm64")
		if self.amd64:
			self.build_arch_list.append("amd64")
		if self.mips64:
			self.build_arch_list.append("mips64le")
		self.build_arch_list.remove("liumou")

	def write(self, arch):
		"""
		写入控制文件信息
		:param arch: 架构
		:return:
		"""
		txt = f"""Package: com.liumou.pings
Version: {self.version}
Section: utils
Priority: optional
Architecture: {arch}
Homepage: https://liumou.site
Maintainer: 坐公交也用券 <liumou.site@qq.com>
Description: 这是一个使用go编写的ping程序\n"""
		try:
			with open(file=self.control, mode='w', encoding="utf8") as w:
				w.write(txt)
		except Exception as e:
			logger.error(str(e))
			sys.exit(3)

	def chmod(self):
		logger.debug('正在授权...')
		os.chdir(self.files)
		print(os.getcwd())
		os.system(f"chmod 0755 {self.postinst}")
		os.system(f"chmod 0755 {self.postrm}")
		os.system(f"chmod 0755 {self.control}")
		os.system(f"chmod -R 0755 {self.debian}")

	def cp_cmd(self, src, dst, name):
		"""
		Copy Command Exec
		:param name:
		:param src:
		:param dst:
		:return:
		"""
		logger.debug(f"name: {name}")
		if name == "dir":
			logger.debug(f"self.work: {self.work}")
			os.chdir(self.work)
		c = f"cp -rf {src} {dst}"
		print(c)
		if os.system(c) == 0:
			logger.info(f"{name}: 复制成功")
		else:
			logger.debug(os.getcwd())
			logger.error(f"{name}: 复制失败")
			sys.exit(2)
		if name == "dir":
			os.chdir(self.home)

	def build(self):
		os.chdir(self.home)
		logger.debug(f"当前目录：{os.getcwd()}")
		c = f"dpkg-deb -b -Z gzip {os.path.basename(str(self.pack_root))}"
		print(f"执行: {c}")
		if os.system(c) == 0:
			logger.info("构建成功")
		else:
			logger.error("构建失败")
			sys.exit(2)

	def to_html(self):
		"""
		发布到网站
		:return:
		"""
		for i in ["latest", self.version]:
			self.client = f"com.liumou.pings_{self.set_arch}-linux_{i}.deb"
			self.dst = f"/root/git/Nginx/html/clm/pings/{self.client}"
			src = os.path.join(self.home, f"com.liumou.pings_{self.version}.deb")
			c = f"cp -rf {src} {self.dst}"
			print(c)
			if os.system(c) == 0:
				print("复制成功")
				self.publish_list.append(f"http://clm.liumou.site/pings/{self.client}")
			else:
				print("发布失败")

	def install(self):
		logger.debug(self.set_arch, " -> ", self.arch)
		if self.set_arch == self.arch:
			c = f"dpkg -i {self.build_client}"
			print(c)
			if os.system(c) == 0:
				print("安装成功")
				return True
			logger.error("安装失败")
			sys.exit(1)

	def delete(self):
		"""
		删除残留文件
		:return:
		"""
		rl = [f"rm -rf {self.pack_root}", f"rm -rf {self.build_client}"]
		for i in rl:
			print(i)
			os.system(i)

	def start(self):
		"""
		开始
		:return:
		"""
		if len(self.build_arch_list) >= 1:
			for a in self.build_arch_list:
				self.set_arch = a
				self.client = f"com.liumou.pings_{self.set_arch}-{self.version}.deb"
				f = os.path.join(self.work, f"client/pings_linux-{a}.zip")
				self.cp_cmd(src="./BuildDeb/com.liumou.pings", dst=self.pack_root, name="dir")
				self.write(arch=a)
				self.cp_cmd(src=f, dst=os.path.join(self.files, os.path.basename(f)), name="bin")
				# self.cp_cmd(src=f, dst=self.usr_bin_client, name="usr_bin_client")
				self.chmod()
				# r = f"rm -f {os.path.join(self.usr_bin_dir, 'Home.url')}"
				# print(r)
				# os.system(r)
				self.build()
				self.install()
				self.to_html()
				if len(self.publish_list) >= 1:
					for i in self.publish_list:
						print(i)
				self.delete()


if __name__ == "__main__":
	bb = BuildDeb(arm64=True, amd64=True, mips64=True)
	bb.start()
